#pragma once

class M2VideoLoadTask : public IGraphicsTask
{
	bool execute() {
		for(ui32 i = 0; i < modelInfo.getNumPasses(); ++i) {
			const M2RenderPass& pass = modelInfo.getPass(i);
			Texture* tex = sTexture.GetTexture(pass.Texture);
			mRenderer->addTexture(tex);
		}

		if(modelInfo.getNumIndices() == 0 || modelInfo.getNumVertices() == 0)
			return true;

		IDirect3DVertexBuffer9* vb = NULL;
		auto res = sD3D->CreateVertexBuffer(modelInfo.getNumVertices() * sizeof(MdxVertex), D3DUSAGE_WRITEONLY, D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1, D3DPOOL_MANAGED, &vb, NULL);
		if(vb == NULL) {
			std::stringstream strm;
			strm << "Unable to create vertex buffer: " << DXGetErrorDescription(res);
			throw std::exception(strm.str().c_str());
		}

		void* pData = NULL;
		vb->Lock(0, 0, &pData, 0);
		memcpy(pData, modelInfo.getVertices(), modelInfo.getNumVertices() * sizeof(MdxVertex));
		vb->Unlock();

		IDirect3DIndexBuffer9* ibu = NULL;
		sD3D->CreateIndexBuffer(modelInfo.getNumIndices() * 2, D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &ibu, NULL);
		ibu->Lock(0, 0, &pData, 0);
		memcpy(pData, modelInfo.getIndices(), 2 * modelInfo.getNumIndices());
		ibu->Unlock();

		mRenderer->setVertices(vb);
		mRenderer->setIndices(ibu);

		return true;
	}

	void finish() { }

	M2Info& modelInfo;
	M2BatchRender* mRenderer;

public:
	M2VideoLoadTask(M2BatchRender* renderer, M2Info& modInfo) : mRenderer(renderer), modelInfo(modInfo) {
	}
};